package com.neusoft.utils.res.min;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.neusoft.utils.config.SystemConfig;
import com.neusoft.utils.convert.ConvertUtils;
import com.neusoft.utils.file.FileUtils;
import com.neusoft.utils.res.compressor.TResCompressorUtils;
import com.neusoft.utils.string.StringUtil;
import com.neusoft.utils.tpl.bean.ResBean;
import com.neusoft.utils.tpl.help.ReadJsonToMap;
import com.neusoft.utils.web.RequestUtils;

public class CssMinUtils {
	private static final String charset = "UTF-8";
	public static final String configPath = "config/css.json";
	public static String genSrc(String src) {
		HttpServletRequest req = RequestUtils.getRequest();
		String base = RequestUtils.getContextPath();
		Map<String, String> configMap = ReadJsonToMap.read(getFile(configPath));
		String[] cssSrcs = src.split(",");
		List<ResBean> resList = new ArrayList<ResBean>();
		for (String cssStr : cssSrcs) {
			if (null == configMap.get(cssStr)) {
				boolean isCdn = isCdn(cssStr);
				long time = getFileTime(cssStr, isCdn);
				cssStr = getFileStr(cssStr, isCdn);
				resList.add(new ResBean().setPath(cssStr).setTime(time).setIsCdn(isCdn));
			} else {
				String[] cssSubSrcs = configMap.get(cssStr).split(",");
				for (String cssSubSrc : cssSubSrcs) {
					boolean isCdn = isCdn(cssSubSrc);
					long time = getFileTime(cssSubSrc, isCdn);
					cssSubSrc = getFileStr(cssSubSrc, isCdn);
					resList.add(new ResBean().setPath(cssSubSrc).setTime(time).setIsCdn(isCdn));
				}
			}
		}
		String result = "";
		boolean orgFlag = false;
		if(StringUtil.isNull(SystemConfig.getProperty("res.release"))||"false".equals(SystemConfig.getProperty("res.release"))){
			orgFlag = true;
		}
		String s = req.getQueryString();
		if (null != s && !StringUtil.isBlank(s)) {
			if (s.endsWith("@")) {
				orgFlag = true;
			}
		}
		if (!orgFlag) {
			result = renderCssList(resList, base);
		} else {
			result = renderOrgCssList(resList, base);
		}
         return result;
	}

	public static String renderCssList(List<ResBean> resList, String base) {
		StringBuffer resultSb = new StringBuffer();
		for (ResBean resBean : resList) {
			if (resBean.getIsCdn()) {
				resultSb.append(StringUtil.format("<link rel=\"stylesheet\" href=\"{0}\">", resBean.getPath())).append("\r\n");
			} else {
				String path = resBean.getPath();
				File orgJsFile = new File(RequestUtils.getWebRealPath(path));
				 String genFilePath=path;
				if (!path.endsWith(".min.css")) {
					//生成
					String fileName=StringUtil.substringAfterLast(path, "/");
					fileName=fileName.substring(0,fileName.length() - ".css".length());
				    String genFileName=fileName+"-"+ConvertUtils.toString(resBean.getTime())+".css";
				    genFilePath=StringUtil.substringBeforeLast(path, "/")+"/"+genFileName;
					File minJsFile = new File(RequestUtils.getWebRealPath(genFilePath));
					if (!minJsFile.exists()) {
						String jsStr="";
						try {
							jsStr = TResCompressorUtils.cssCompressor(FileUtils.readFileToString(orgJsFile, charset));
							FileUtils.writeStringToFile(minJsFile, jsStr, charset);	
						} catch (IOException e) {
							e.printStackTrace();
						}	
					}
					//path = path.substring(0, path.length() - ".css".length()) + ".min.css";
				}
				resultSb.append(StringUtil.format("<link rel=\"stylesheet\" href=\"{0}/{1}?v={2}\">", base, genFilePath,resBean.getTime().toString())).append("\r\n");
			}
		}
		return resultSb.toString();
	}

	public static String renderOrgCssList(List<ResBean> resList, String base) {
		StringBuffer resultSb = new StringBuffer();
		for (ResBean resBean : resList) {
			if (resBean.getIsCdn()) {
				resultSb.append(StringUtil.format("<link rel=\"stylesheet\" href=\"{0}\">", resBean.getPath())).append("\r\n");
			} else {
				String path = resBean.getPath();
				resultSb.append(StringUtil.format("<link rel=\"stylesheet\" href=\"{0}/{1}?v={2}\">", base, path, resBean.getTime().toString())).append("\r\n");
			}
		}
		return resultSb.toString();
	}

	private static long getFileTime(String path, boolean isCdn) {
		if (isCdn) {
			return 1L;
		}
		return new File(RequestUtils.getWebRealPath(path)).lastModified();
	}

	private static boolean isCdn(String path) {
		if (path.startsWith("@")) {
			return true;
		}
		return false;
	}

	private static String getFileStr(String path, boolean isCdn) {
		if (isCdn) {
			return path.substring(1, path.length());
		}
		return path;
	}

	private static File getFile(String path) {
		return new File(RequestUtils.getWebRealPath(path));
	}
}
